<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="isShow=true"
            >新增角色</el-button>
            <el-dialog :title="showTitle" :visible="isShow" @close="closeDialog">
              <el-form ref="roleForm" :model="form" label-width="100px">
                <el-form-item label="角色名称">
                  <el-input v-model="form.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色描述">
                  <el-input v-model="form.description" placeholder="请输入角色描述" />
                </el-form-item>
              </el-form>

              <template #footer>
                <el-button @click="isShow=false">取消</el-button>
                <el-button type="primary" @click="addRole">确认</el-button>
              </template>
            </el-dialog>
            <!-- 表格 -->
            <el-table :loading="loading" :data="list">
              <el-table-column type="index" label="序号" width="120" :index="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template v-slot="{row}">
                  <el-button size="small" type="success" @click="fenpei(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="update(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分配权限的弹层 -->
            <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog" @open="openAssignDialog">
              <el-tree
                ref="tree"
                v-loading="treeLoading"
                :data="permissionData"
                :props="{ label: 'name' }"
                :default-expand-all="true"
                :show-checkbox="true"
                :check-strictly="true"
                node-key="id"
              />
              <template #footer>
                <div style="text-align: right;">
                  <el-button @click="closeAssignDialog">取消</el-button>
                  <el-button type="primary" @click="clickAssign">确定</el-button>
                </div>
              </template>
            </el-dialog>
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />

          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import { reqGetRoleList, reqAddRole, reqDelRole, reqUpdateRole, reqGetRole, reqAssignPerm } from '@/api/setting'
import { reqGetCompany } from '@/api/company'
import { mapState } from 'vuex'
import { reqGetPermissionList } from '@/api/permisson'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      list: [],
      page: 1, // 当前页
      pagesize: 5, // 每页条数
      total: 0, // 总条数
      isShow: false,
      updateShow: false,
      form: {
        name: '',
        description: ''
      },
      loading: false,
      companyForm: {},
      showAssignDialog: false,
      roleId: '',
      permissionData: [], // 权限数据
      treeLoading: false
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    },
    index() {
      return (this.page - 1) * this.pagesize + 1
    }
  },
  created() {
    this.getRoleList() // 获取角色列表
    this.getCompany()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { data: res } = await reqGetRoleList(this.page, this.pagesize)
      const { total, rows } = res
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getRoleList()
    },
    async addRole() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        if (this.form.id) {
          await reqUpdateRole(this.form)
          this.$message.success('修改成功')
        } else {
          await reqAddRole(this.form)
          this.$message.success('添加成功')
        }
        this.closeDialog()
        this.getRoleList()
      })
    },
    closeDialog() {
      this.isShow = false
      // 重置表单数据
      this.form.name = ''
      this.form.description = ''
    },
    async delRole(id) {
      this.$confirm('确定要删除该角色吗？', '提示').then(async() => {
        await reqDelRole(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.getRoleList() // 重新加载数据
        this.$message.success('删除角色成功')
      }).catch(error => {
        console.log(error)
      })
    },
    async update(id) {
      const { data: res } = await reqGetRole(id)
      this.form = res
      this.isShow = true
    },
    async getCompany() {
      // console.log(this.userInfo)
      const { data: res } = await reqGetCompany(this.userInfo.companyId)
      // console.log(res)
      this.companyForm = res
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    fenpei(id) {
      this.showAssignDialog = true
      this.roleId = id
      // console.log(id)
    },
    async  openAssignDialog() {
      this.treeLoading = true
      // 发送请求  获取权限列表
      const { data: permissionData } = await reqGetPermissionList()
      this.permissionData = tranListToTreeData(permissionData, '0')
      // console.log(this.permissionData)
      // 发送请求  获取已有权限
      const { data: roleDetail } = await reqGetRole(this.roleId)
      // console.log(roleDetail.permIds)
      this.$refs.tree.setCheckedKeys(roleDetail.permIds)
      this.treeLoading = false
    },
    async clickAssign() {
      await reqAssignPerm({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('分配成功')
      this.showAssignDialog = false
    }

  }
}
</script>
